<template>
  <el-dialog :model-value="dialogVisible" :title="state.title" width="45%" align-center @closed="handleCancel">
    <el-form
      ref="refForm"
      :model="form.data"
      :rules="form.rules"
      label-position="right"
      :label-width="110"
      style="padding-right: 15px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item prop="userName" label="姓名">
            <el-input v-model="form.data.userName" placeholder="请输入姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="userCode" label="编号">
            <el-input v-model="form.data.userCode" placeholder="请输入编号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="loginName" label="账号">
            <el-input v-model="form.data.loginName" placeholder="请输入账号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="password" label="密码">
            <el-input v-if="state.isCreate" v-model="form.data.password" placeholder="请输入密码">
              <template #append>
                <el-link :underline="false" @click="handleGeneratePwd">随机生成</el-link>
              </template>
            </el-input>
            <el-input v-else placeholder="**********" type="password" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="positionId" label="职位">
            <el-select v-model="form.data.positionId" clearable placeholder="请选择职位">
              <el-option
                v-for="item in data.position"
                :key="item.positionId"
                :label="item.positionName"
                :value="item.positionId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="expiryDate" label="账号有效期">
            <el-date-picker
              v-model="form.data.expiryDate"
              type="date"
              placeholder="请选择账号有效期"
              :disabled-date="disabledDate"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="cellphone" label="手机号码">
            <el-input v-model="form.data.cellphone" placeholder="请输入手机号码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="email" label="邮箱地址">
            <el-input v-model="form.data.email" placeholder="请输入邮箱地址"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="gender" label="性别">
            <el-radio-group v-model="form.data.gender">
              <el-radio label="1">男</el-radio>
              <el-radio label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="userStatus" label="状态">
            <el-radio-group v-model="form.data.userStatus">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-form-item prop="photo">
        <el-input v-model="form.data.photo" autocomplete="off" placeholder="请输入照片"></el-input>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="handleSave">保 存</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { withDefaults, computed, reactive, ref, nextTick, onMounted } from 'vue'
import {
  ElDialog,
  ElMessage,
  ElForm,
  ElFormItem,
  ElInput,
  ElRadioGroup,
  ElRadio,
  ElDatePicker,
  ElSelect,
  ElOption
} from 'element-plus'
import { util, validator } from '@/utils'
import { userApi } from '@/api/modules/system/user'
import type { User } from '@/api/modules/system/user'
import { positionApi } from '@/api/modules/system/position'
import type { Position } from '@/api/modules/system/position'

const props = withDefaults(defineProps<{ visible: boolean }>(), {
  visible: false
})
const emits = defineEmits(['success', 'update:visible'])

const data = reactive({ position: [] as Position[] })
const findPosition = () => {
  positionApi.findList().then(resp => {
    if (resp.success) {
      data.position = resp.data
    }
  })
}
onMounted(findPosition)

const dialogVisible = computed(() => props.visible)

const refForm = ref()
const form = reactive<{ data: User; rules: any }>({
  data: { userStatus: 1 } as User,
  rules: {
    userName: [{ required: true, message: '请输入姓名' }],
    userCode: [{ required: true, message: '请输入编号' }],
    loginName: [{ required: true, message: '请输入账号' }],
    password: [{ required: true, message: '请输入密码' }],
    cellphone: [{ validator: validator.verifyCellphone, trigger: 'blur' }],
    email: [{ validator: validator.verifyEmail, trigger: 'blur' }]
  }
})

const state = computed(() => {
  if (form.data.userId) {
    return { isCreate: false, title: '修改用户' }
  } else {
    return { isCreate: true, title: '新建用户' }
  }
})

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now()
}

const handleSave = () => {
  refForm.value.validate((valid: boolean) => {
    if (valid) {
      saveCallback(userApi.save(form.data))
    }
  })
}
const saveCallback = (promise: Promise<AxiosType.Response>) => {
  promise.then(resp => {
    if (resp.success) {
      ElMessage.success(`已${state.value.title} [ ${form.data.userName} ]`)
      emits('success')
      handleCancel()
    } else {
      ElMessage.error(resp.message)
    }
  })
}

const handleCancel = () => {
  form.data = { userStatus: 1 } as User
  refForm.value.resetFields()
  emits('update:visible', false)
}

const setFormData = (data: User) => {
  nextTick(() => (form.data = { ...util.cloneObject(data), password: '*' }))
}

const handleGeneratePwd = () => {
  form.data.password = util.randomStr(8)
}
defineExpose({ setFormData })
</script>

<style lang="scss" scoped></style>
